#include "loginwindow.h"
#include "ui_loginwindow.h"
#include <QMessageBox>

LoginWindow::LoginWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::LoginWindow)
{
    ui->setupUi(this);

    waitCnt = 0;
    text.append("Login");

    init();
}

LoginWindow::~LoginWindow()
{
    delete ui;
}

void LoginWindow::init()
{
    this->setWindowTitle("Please to Login");
    ui->le_ipAddr->setText("192.168.2.100");
    ui->le_port->setText("8080");
}

void LoginWindow::timerFinish()
{
    if(tcpClient->state() == QTcpSocket::ConnectedState){
        waitCnt = 0;
        time->stop();

        this->close();

        main = new MainWindow;
        main->main_ipAddr = login_ipAddr;
        main->main_port = login_port;
        main->init();
        main->show();

    }else{
        waitCnt++;

        if(waitCnt%10 == 3)
            text = "Login.";
        else if(waitCnt%10 == 6)
            text = "Login..";
        else if(waitCnt%10 == 9)
            text = "Login...";
        ui->btn_login->setText(text);

        if(waitCnt == 50){
            time->stop();
            waitCnt = 0;
            ui->btn_login->setText("Login");

            QMessageBox::warning(this, "Warning", "Please to Check params\nand Login again!", QMessageBox::Ok);
        }
    }
}

void LoginWindow::on_btn_login_clicked()
{
    login_ipAddr = ui->le_ipAddr->text();
    login_port = ui->le_port->text();

    tcpClient = new QTcpSocket(this);
    tcpClient->connectToHost(login_ipAddr, login_port.toInt());

    time = new QTimer(this);
    time->setInterval(100);

    connect(time, SIGNAL(timeout()), this, SLOT(timerFinish()));
    time->start();
}

void LoginWindow::on_btn_logout_clicked()
{
    this->close();
}
